

# 抽取单独功能　封装成函数
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from mall import settings
from users.models import User


def generic_verify_url(user_id,email):
    # 创建序列化器　第一参数　默认使用配置中秘钥　进行加密　第二参数是时间　过期时间
    serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)

    data = {
        'user_id':user_id,
        'email':email
    }
    # 进行加密　
    tokenid = serializer.dumps(data)
    # 生成的byte类型　转成字符串

    verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + tokenid.decode()
    return verify_url


def check_verify_url(token):

    serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)

    try:
        token = serializer.loads(token)
    except Exception:
        return None

    else:
        user_id = token.get('user_id')
        email = token.get('email')
        try:
            user = User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            user = None

        else:
            return user

